package com.lib.servlet.member;

import com.alibaba.fastjson.JSON;
import com.lib.common.Constant;
import com.lib.dao.ex.UpdateDaoException;
import com.lib.entity.Admin;
import com.lib.entity.JsonResult;
import com.lib.entity.Member;
import com.lib.service.MemberService;
import com.lib.service.ex.EmptyArgumentException;
import com.lib.service.ex.InValidArgumentException;
import com.lib.service.ex.RecordIsFoundException;
import com.lib.service.ex.ServiceException;
import com.lib.util.ParamUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 修改会员
 */

@WebServlet(name = "ModifyMemberServlet", value = "/admin/ModifyMemberServlet.do")
public class ModifyMemberServlet extends HttpServlet {
    private MemberService memberService = new MemberService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("===="+request.getParameter("idNumber"));
        Admin admin = (Admin) request.getSession().getAttribute(Constant.SESSION_ADMIN);
        Member member = null;
        member = ParamUtil.toBean(request.getParameterMap(),Member.class);
        System.out.println("idNumber ="+member.getIdNumber());
        JsonResult jsonResult = null;
        try {
            memberService.modifyMember(member);
            jsonResult = JsonResult.getSuccessJR();
        } catch (EmptyArgumentException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,e.getMessage());
        } catch (InValidArgumentException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_INVALID_ARGUEMENT,e.getMessage());
        } catch (RecordIsFoundException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_RECORD_IS_FOUND,e.getMessage());
        } catch (UpdateDaoException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_UPDATE,e.getMessage());
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_ERROR,e.getMessage());
        }
        System.out.println("----jsonResult = " + JSON.toJSONString(jsonResult));
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(jsonResult));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
